﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHibernate.Linq;
using System.Reflection;

namespace GLAD_prototype
{
    public class CRUD
    {
        public static void CopyProperties<T>(T source, T destination)
        {
            // Iterate the Properties of the destination instance and  
            // populate them from their source counterparts  
            PropertyInfo[] destinationProperties = destination.GetType().GetProperties();
            foreach (PropertyInfo destinationPi in destinationProperties)
            {
                PropertyInfo sourcePi = source.GetType().GetProperty(destinationPi.Name);
                destinationPi.SetValue(destination, sourcePi.GetValue(source, null), null);
            }
        }

        public static void updateDGV<T>(DataGridView dgv)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                var makeQuery = (from item in session.Query<T>()
                                 select item).ToList();
                if (makeQuery.Count > 0)
                    dgv.DataSource = makeQuery;
            }
        }

        public static void Insert<T>(T item)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(item);
                    transaction.Commit();
                }
            }
        }

        public static void Update<T>(T source, Func<T, bool> wh)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                T destination = session.Query<T>()
                                   .Where(wh)
                                   .Select(m => m).Single();

                CopyProperties<T>(source, destination);

                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(destination);
                    transaction.Commit();
                }
            }
        }

        public static void Delete<T>(Func<T, bool> wh)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                T item = session.Query<T>()
                                   .Where(wh)
                                   .Select(m => m).Single();

                using (var transaction = session.BeginTransaction())
                {
                    session.Delete(item);
                    transaction.Commit();
                }
            }
        }
    }
}
